// @/src/api/OrderApi.js
import axiosInstance from '@/utils/request'

/**
 * 创建订单API
 * POST /orders/operation/create
 * @param {Object} orderData - 订单创建请求数据
 * @param {OrdersDTO} orderData.ordersDTO - 订单基本信息
 * @param {Array<OrdersItemsDTO>} orderData.orderItemsDTOList - 订单商品明细列表
 * @param {Array<Long>} orderData.cartIds - 购物车ID列表（用于创建订单后清除购物车）
 * @returns {Promise} Axios Promise，返回ResponseResult<OrdersDTO>
 */
export const createOrderAPI = (orderData) => {
    return axiosInstance.post('/product/orders/operation/create', orderData, {
        headers: {
            'Content-Type': 'application/json'
        }
    })
}

/**
 * 获取用户订单列表API
 * GET /orders/operation/list
 * @param {Object} params - 查询参数
 * @param {Integer} params.orderStatus - 订单状态(可选)：0-订单取消 1-待支付 2-已支付待发货 3-已发货 4-已签收 5-订单完成 6-申请售后 7-退货退款
 * @param {Integer} params.page - 页码，默认1
 * @param {Integer} params.size - 每页数量，默认10
 * @returns {Promise} Axios Promise，返回ResponseResult<List<OrdersDTO>>
 */
export const getOrdersListAPI = (params = {}) => {
    const { orderStatus, page = 1, size = 10 } = params;

    // 构建查询参数
    const queryParams = {
        page,
        size
    };

    // 只有当orderStatus有值时才添加到参数中
    if (orderStatus !== undefined && orderStatus !== null) {
        queryParams.orderStatus = orderStatus;
    }

    return axiosInstance.get('/product/orders/operation/list', {
        params: queryParams,
        headers: {
            'Content-Type': 'application/json'
        }
    });
};

/**
 * 订单状态枚举 - 便于前端使用
 */
export const ORDER_STATUS = {
    CANCELLED: 0,      // 订单取消
    PENDING_PAYMENT: 1, // 待支付
    PAID_PENDING_SHIP: 2, // 已支付待发货
    SHIPPED: 3,        // 已发货
    RECEIVED: 4,       // 已签收
    COMPLETED: 5,      // 订单完成
    AFTER_SALE: 6,     // 申请售后
    REFUNDED: 7        // 退货退款
};

/**
 * 获取订单状态文本描述
 * @param {Integer} status - 订单状态码
 * @returns {String} 状态描述
 */
export const getOrderStatusText = (status) => {
    const statusMap = {
        [ORDER_STATUS.CANCELLED]: '订单取消',
        [ORDER_STATUS.PENDING_PAYMENT]: '待支付',
        [ORDER_STATUS.PAID_PENDING_SHIP]: '已支付待发货',
        [ORDER_STATUS.SHIPPED]: '已发货',
        [ORDER_STATUS.RECEIVED]: '已签收',
        [ORDER_STATUS.COMPLETED]: '订单完成',
        [ORDER_STATUS.AFTER_SALE]: '申请售后',
        [ORDER_STATUS.REFUNDED]: '退货退款'
    };
    return statusMap[status] || '未知状态';
};

/**
 * 获取订单状态对应的颜色类名
 * @param {Integer} status - 订单状态码
 * @returns {String} CSS类名
 */
export const getOrderStatusColor = (status) => {
    const colorMap = {
        [ORDER_STATUS.CANCELLED]: 'status-cancelled',
        [ORDER_STATUS.PENDING_PAYMENT]: 'status-pending',
        [ORDER_STATUS.PAID_PENDING_SHIP]: 'status-paid',
        [ORDER_STATUS.SHIPPED]: 'status-shipped',
        [ORDER_STATUS.RECEIVED]: 'status-received',
        [ORDER_STATUS.COMPLETED]: 'status-completed',
        [ORDER_STATUS.AFTER_SALE]: 'status-after-sale',
        [ORDER_STATUS.REFUNDED]: 'status-refunded'
    };
    return colorMap[status] || 'status-unknown';
};

/**
 * 根据订单ID获取订单详情API
 * GET /orders/operation/detail/{orderId}
 * @param {Long} orderId - 订单ID
 * @returns {Promise} Axios Promise，返回ResponseResult<OrderDetailDTO>
 */
export const getOrderDetailAPI = (orderId) => {
    return axiosInstance.get(`/product/orders/operation/detail/${orderId}`, {
        headers: {
            'Content-Type': 'application/json'
        }
    });
};

/**
 * 订单操作API - 取消订单
 * PUT /orders/operation/cancel/{orderId}
 * @param {Long} orderId - 订单ID
 * @returns {Promise} Axios Promise
 */
export const cancelOrderAPI = (orderId) => {
    return axiosInstance.put(`/product/orders/operation/cancel/${orderId}`, {}, {
        headers: {
            'Content-Type': 'application/json'
        }
    });
};

/**
 * 订单操作API - 确认收货
 * PUT /orders/operation/confirm-receipt/{orderId}
 * @param {Long} orderId - 订单ID
 * @returns {Promise} Axios Promise
 */
export const confirmReceiptAPI = (orderId) => {
    return axiosInstance.put(`/product/orders/operation/confirm-receipt/${orderId}`, {}, {
        headers: {
            'Content-Type': 'application/json'
        }
    });
};

/**
 * 订单操作API - 申请退款/退货
 * POST /orders/operation/refund/{orderId}
 * @param {Long} orderId - 订单ID
 * @param {Object} refundData - 退款申请数据
 * @param {String} refundData.reason - 退款原因
 * @param {String} refundData.description - 详细描述
 * @returns {Promise} Axios Promise
 */
export const applyRefundAPI = (orderId, refundData) => {
    return axiosInstance.post(`/product/orders/operation/refund/${orderId}`, refundData, {
        headers: {
            'Content-Type': 'application/json'
        }
    });
};

/**
 * 构建订单创建请求数据的辅助函数
 * @param {Object} params - 参数对象
 * @param {Long} params.userId - 用户ID
 * @param {Long} params.addressId - 收货地址ID
 * @param {Integer} params.paymentType - 支付方式(1-支付宝 2-微信 3-银行卡)
 * @param {String} params.remark - 订单备注
 * @param {Array} params.selectedItems - 选中的购物车商品列表
 * @param {Array<Long>} params.cartIds - 购物车ID列表
 * @returns {Object} 格式化的订单创建请求数据
 */
export const buildOrderCreateRequest = ({
    userId,
    addressId,
    paymentType = 1, // 默认支付宝
    remark = '',
    selectedItems,
    cartIds
}) => {
    // 构建订单基本信息 OrdersDTO
    const ordersDTO = {
        userId: userId,
        addressId: addressId,
        paymentType: paymentType,
        orderStatus: 1, // 默认待支付状态
        remark: remark
    }

    // 构建订单商品明细列表 OrdersItemsDTO[]
    const orderItemsDTOList = selectedItems.map(item => ({
        productId: item.productId,
        quantity: item.quantity,
        price: item.price
    }))

    // 返回完整的请求数据结构
    return {
        ordersDTO,
        orderItemsDTOList,
        cartIds
    }
}